import json
import time
import hashlib
import random
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import base64
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend
from xml.etree import ElementTree as ET


# 微信文档:https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_8_3.shtml


# 随机字符串，长度为32个字符以下
def RandomStr():
    # 大写字母中生成随机12位字符串数据chr用于将65-90(阿斯克码)转为大写字母
    return "".join([chr(random.randint(65, 90)) for _ in range(12)])


def md5(string):
    """MD5加密,使用settings的key来加盐,和redis一样需要字节类"""
    hash_object = hashlib.md5(string.encode('utf-8'))
    return hash_object.hexdigest()


# 参数：商户私钥 和 参与签名字段
"""
参与签名字段及格式如下：
小程序appId
时间戳
随机字符串
订单详情扩展字符串
"""


def rsa_sign(private_key, sign_str):
    """RSA加密"""
    message = sign_str.encode('UTF-8')
    signature = private_key.sign(data=message, padding=PKCS1v15(), algorithm=SHA256())
    sign = base64.b64encode(signature).decode('UTF-8').replace('\n', '')
    return sign


# AEAD_AES_256_GCM解密
def decrypt(nonce, ciphertext, associated_data):
    # APIv3密钥
    key = "Your32Apiv3Key"
    # 转为字节类型
    key_bytes = str.encode(key)
    nonce_bytes = str.encode(nonce)
    ad_bytes = str.encode(associated_data)
    # base64解码
    data = base64.b64decode(ciphertext)
    # AESGCM解密
    aesgcm = AESGCM(key_bytes)
    # 返回结果
    return aesgcm.decrypt(nonce_bytes, data, ad_bytes)


# 获取微信支付所需参数(md5版的)
def PayTest():
    data = {
        # 小程序appid
        'appId': "wxd678efh567hg6787",
        # 随机字符串小于32位
        'nonceStr': "ibuaiVcKdpRxkhJA",
        # 这个需要先微信访问url:https://api.mch.weixin.qq.com/v3/pay/transactions/jsapi
        'package': "prepay_id=wx2017033010242291fcfe0db70013231072",
        # 加密类型
        'signType': "MD5",
        # 时间
        "timeStamp": str(time.time()),
    }
    # 小程序密钥
    key = "qazwsxedcrfvtgbyhnujmikolp111111"
    unsigned_string = "&".join(
        ["{0}={1}".format(k, data[k]) for k in sorted(data)] + ["{0}={1}".format("key", key), ])
    sign = md5(unsigned_string).upper()
    data['paySign'] = sign
    # 返回给前端
    print(data)


# rsa版


# 微信支付回调路由(模拟 公网域名必须为https)
# 获取ip:request.META.get('REMOTE_ADDR')
def pay_notify(request):
    # 1.post请求 2.将微信返回的xml转字典
    # 2.将sign从字典拿出做校验(排序+加密)
    # 3.如果一致更改订单状态
    # 4.返回给微信格式

    pass


if __name__ == '__main__':
    # PayTest()
    tx_time = "62465CA2"
    # ad10eb77d4c7baf58eb3fd0504c4e07b
    # ad10eb77d4c7baf58eb3fd0504c4e07b
    tx_secret = md5('add791fe6b9582f213990c8ecd33c773'+"ss"+tx_time)
    print(tx_secret)